package com.tomato.wangzh.client;

import com.tomato.wangzh.grpc.common.HelloRequest;
import com.tomato.wangzh.grpc.common.HelloResponse;
import com.tomato.wangzh.grpc.common.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * <p>
 * Copyright: (C), 2021/6/4 15:45
 * <p>
 * <p>
 * Company: Information & Data Security Solutions Co., Ltd.
 *
 * @author neil.wang@idss-cn.com
 * @version 1.0
 */
public class GrpcClient {

    private static final Logger logger = Logger.getLogger(GrpcClient.class.getName());


    // 与服务端通信通道
    private ManagedChannel channel;

    // 阻塞stub 用于服务端通信
    private HelloServiceGrpc.HelloServiceBlockingStub stub;

    public GrpcClient(Integer port, String ip) {
        this.channel =
                ManagedChannelBuilder
                        .forAddress(ip, port)
                        .usePlaintext() // 使用文本传输 这个是最简的方式
                        .build();   // 构建通信channel

        this.stub = HelloServiceGrpc.newBlockingStub(channel);
        logger.info("init client");
    }


    /**
     * 等待通道关闭直到达到超时时间放弃
     * @throws InterruptedException
     */
    public void shutdown() throws InterruptedException {
        if (channel != null) {
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            logger.info("shut down client channel");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        GrpcClient client = null;
        try {
            // 创建客户端
            client = new GrpcClient(13451 , "localhost");
            // 构建请求参数
            HelloRequest request = HelloRequest.newBuilder().setParam("test").build();

            // 远程调用方法 超过5秒还没响应
            HelloResponse response = client.stub.withDeadlineAfter(5,TimeUnit.SECONDS).hellRpcTest(request);

            // 输出结果
            System.out.println(response.getResult());
        } finally {
          if (client != null) {
              // 关闭通道
              client.shutdown();
          }
        }
    }
}
